package com.litree.service.utils;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class FileUpAndDown {

    /** image最大size  1M*/
	public final static int PRODUCTPATH_IMAGE_MAX_SIZE = 1048576;//1048576;

    @SuppressWarnings("resource")
	public String fileUpload(String imgPath,String fileName) {
    	String message = "";
        try {
            File f = new File(imgPath,fileName); 
            if(!f.isFile()){
            	message="对不起,你上传的文件不存在!!!";
                return message;
            }
            if(!fileName.toLowerCase().endsWith(".jpg")&&!fileName.toLowerCase().endsWith(".png")){
                message="对不起,你上传的文件格式不允许!!!";
                return message;
            }  
            FileInputStream inputStream = new FileInputStream(f);
            if (inputStream.available()>PRODUCTPATH_IMAGE_MAX_SIZE){
            	  message="上传图片超过最大上传大小1M,请调整后重新上传。";
                  return message;
            }  
           
            byte[] fileArray=getFileContent(f);
            message = new BASE64Encoder().encode(fileArray);
        } catch (Exception e) {
            e.printStackTrace();
            message = "对不起,文件上传失败了!!!!";
         
        }
            return message;
    }
    
    
	@SuppressWarnings("resource")
	public byte[] getFileContent(File file) throws IOException {  
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {  
            System.out.println("file too big...");  
            return null;
        }  
        FileInputStream fi = new FileInputStream(file);  
        byte[] buffer = new byte[(int) fileSize];  
        int offset = 0;  
        int numRead = 0;  
        while (offset < buffer.length  
        && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {  
            offset += numRead;  
        }  
        // 确保所有数据均被读取  
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "  + file.getName());  
        }  
        fi.close();  
        return buffer;  
    }  


	 /**
	  * 将base64字符解码保存文件
	  * @param base64Code
	  * @param targetName
	  * @throws Exception
	  */

	 public static void decoderBase64File(String base64Code, String targetName)
	   throws Exception {
	  byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
	  FileOutputStream out = new FileOutputStream(CommonUtils.getPropertiesBykey("imagePath")+targetName);
	  out.write(buffer);
	  out.close();
	 }

    /** 
     * 改变图片的大小到宽为size，然后高随着宽等比例变化 
     * @param is 上传的图片的输入流 
     * @param os 改变了图片的大小后，把图片的流输出到目标OutputStream 
     * @param size 新图片的宽 
     * @param format 新图片的格式 
     * @throws IOException 
     */  
    public static void resizeImage(InputStream is, OutputStream os, int size, String format) throws IOException {
        BufferedImage prevImage = ImageIO.read(is);   
        int newWidth = (int)(size);  
        int newHeight = (int)(size);  
        BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR);  
        Graphics graphics = image.createGraphics();  
        graphics.drawImage(prevImage, 0, 0, newWidth, newHeight, null);  
        ImageIO.write(image, format, os);  
        os.flush();  
        is.close();  
        os.close();  
    }
    
	 public static void main(String[] args) {
		 FileOutputStream out100=null;
		 FileOutputStream out60=null;
		 FileInputStream fis1=null;
		 FileInputStream fis2=null;
	  try {
	   FileUpAndDown fad = new FileUpAndDown();
	   decoderBase64File(fad.fileUpload("D:/workspace/zlhtml/assets/img/bg", "18.jpg"), "3.jpg");
	   File file1 = new File(CommonUtils.getPropertiesBykey("imagePath"),"3.jpg");
	   File file2 = new File(CommonUtils.getPropertiesBykey("imagePath"),"3.jpg");
	   fis1 = new FileInputStream(file1); 
	   fis2 = new FileInputStream(file2); 
	   out60 = new FileOutputStream(CommonUtils.getPropertiesBykey("imagePath")+"3_60.jpg");
	   out100 = new FileOutputStream(CommonUtils.getPropertiesBykey("imagePath")+"3_100.jpg");
	   resizeImage(fis1, out100, 100, "jpg");
	   resizeImage(fis2, out60, 60, "jpg");
	  } catch (Exception e) {
	   e.printStackTrace();
	  }finally{
		   try {
			   if(out100!=null){  
					out100.close();
			   }
			   if(out60!=null){
				   out60.close();
			   }
			   if(fis1!=null){
				   fis1.close();
			   }
			   if(fis2!=null){
				   fis2.close();
			   }
		} catch (IOException e) {
			e.printStackTrace();
		}
	  }
	 }
}
